﻿#region License
/*
Copyright (c) 2005-2011, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Usings...
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
#endregion

namespace ChatEngine
{
    /// <summary>
    /// 
    /// </summary>
    public class PacketWriter
    {
        /// <summary>
        /// 
        /// </summary>
        private List<Byte> _packet = new List<Byte>();

        /// <summary>
        /// 
        /// </summary>
        private List<Byte> _data = new List<Byte>();

        /// <summary>
        /// 
        /// </summary>
        private UInt16 _type = 0;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        public PacketWriter(UInt16 type)
        {
            this._type = type;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public void WriteByte(Byte input)
        {
            this._data.Add(input);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public void WriteUInt16(UInt16 input)
        {
            this._data.AddRange(BitConverter.GetBytes((UInt16)IPAddress.HostToNetworkOrder((Int16)input)));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public void WriteUInt32(UInt32 input)
        {
            this._data.AddRange(BitConverter.GetBytes((UInt32)IPAddress.HostToNetworkOrder((Int32)input)));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public void WriteBytes(Byte[] input)
        {
            this._data.AddRange(input);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public void WriteString(String input)
        {
            if (String.IsNullOrEmpty(input))
            {
                this._data.AddRange(new byte[] { 0x00, 0x01, 0x00 });
            }
            else
            {
                Int16 length = IPAddress.HostToNetworkOrder((Int16)Encoding.UTF8.GetByteCount(input));
                this._data.AddRange(BitConverter.GetBytes((UInt16)length));
                this._data.AddRange(Encoding.UTF8.GetBytes(input));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Byte[] Finish()
        {
            this._packet.AddRange(BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder((short)this._type)));
            this._packet.AddRange(BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder((short)this._data.Count)));
            this._packet.AddRange(this._data);
            return this._packet.ToArray();
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class PacketReader
    {
        /// <summary>
        /// 
        /// </summary>
        private MemoryStream _stream;

        /// <summary>
        /// 
        /// </summary>
        private BinaryReader _reader;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="packet"></param>
        public PacketReader(ref Byte[] packet)
        {
            this._stream = new MemoryStream(packet);
            this._reader = new BinaryReader(_stream);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Byte ReadByte()
        {
            return _reader.ReadByte();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public UInt16 ReadUInt16()
        {
            return (UInt16)IPAddress.HostToNetworkOrder((Int16)_reader.ReadUInt16());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public UInt32 ReadUInt32()
        {
            return (UInt32)IPAddress.HostToNetworkOrder((Int32)_reader.ReadUInt32());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public Byte[] ReadBytes(int count)
        {
            return _reader.ReadBytes(count);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public String ReadString()
        {
            UInt16 strlen = this.ReadUInt16();
            return Encoding.UTF8.GetString(this.ReadBytes((int)strlen));
        }

        /// <summary>
        /// 
        /// </summary>
        public void Finish()
        {
            _reader.Close();
            _stream.Close();
            _stream.Dispose();
        }
    }
}
